package dao

import (
	"advertising/internal/dal"
	"advertising/internal/models"
	"context"
	"strings"
	"time"

	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type PublishScheduleDevicePlaylist struct{}

func (PublishScheduleDevicePlaylist) Create(ctx context.Context, db *gorm.DB, robotName string, terminalType int, scheduleID, materialID, filePath, fileMd5 string) (err error) {
	m := dal.Use(db).PublishScheduleDevicePlaylist
	var d models.PublishScheduleDevicePlaylist
	d.ID, _ = helper.UUID{}.String()
	d.RobotName = robotName
	d.TerminalType = terminalType
	d.ScheduleID = scheduleID
	d.MaterialID = materialID
	d.FilePath = filePath
	d.FileMd5 = fileMd5
	d.CreatedAt = time.Now().Unix()
	m.WithContext(ctx).Create(&d)
	return nil
}

func (PublishScheduleDevicePlaylist) Delete(ctx context.Context, db *gorm.DB, robotName string, terminalType int, ID string) (err error) {
	m := dal.Use(db).PublishScheduleDevicePlaylist
	tx := m.WithContext(ctx)
	if robotName != "" {
		tx = tx.Where(m.RobotName.Eq(robotName))
	}
	if terminalType != 0 {
		tx = tx.Where(m.TerminalType.Eq(terminalType))
	}
	if ID != "" {
		tx = tx.Where(m.ID.Eq(ID))
	}
	tx.Delete(&models.PublishScheduleDevicePlaylist{})
	return nil
}

func (PublishScheduleDevicePlaylist) List(ctx context.Context, db *gorm.DB, scheduleID, robotName string, terminalType, page, limit int) (res []*models.PublishScheduleDevicePlaylist, count int64, err error) {
	m := dal.Use(db).PublishScheduleDevicePlaylist
	tx := m.WithContext(ctx)
	if scheduleID != "" {
		if strings.Contains(scheduleID, ",") {
			tx = tx.Where(m.ScheduleID.In(strings.Split(scheduleID, ",")...))
		} else {
			tx = tx.Where(m.ScheduleID.Eq(scheduleID))
		}
	}
	if robotName != "" {
		tx = tx.Where(m.RobotName.Eq(robotName))
	}
	if terminalType != 0 {
		tx.Where(m.TerminalType.Eq(terminalType))
	}
	res, count, err = tx.Order(m.ID.Desc()).FindByPage(Offset(page, limit))
	return
}
